package com.huike.controller.adminController;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huike.entity.Admin;
import com.huike.service.IAdminService;
import com.huike.utils.CertificateBulider;
import com.huike.utils.JsonUtils;
import com.huike.utils.MD5Util;
import com.huike.utils.ResultMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Lwen
 * @since 2019-11-12
 */
@RestController
@RequestMapping("/adminController")
public class AdminController {

    @Autowired
    IAdminService adminService;

    /**
     * 解决页面传来时间格式转换失败问题
     * @param binder
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * 后台登录控制器
     * @return
     */
    @RequestMapping("/loginAction")
    @ResponseBody
    public ResultMessage Login(HttpServletRequest request, HttpServletResponse response, Admin admin){
        admin.setPassword(MD5Util.encrypt(admin.getPassword()));
        HttpSession session = request.getSession();
        session.removeAttribute("admin");
        Admin admin2 = adminService.loginFun(admin);
        if (admin2==null){
            return ResultMessage.fail();
        }
        session.setAttribute("admin",admin2);
            return ResultMessage.success();
    }

    /**
     * 修改密码方法
     * @param request
     * @param response
     * @param old_password
     * @param new_password
     * @return
     */
    @RequestMapping("/alterPasswordFunc")
    @ResponseBody
    public ResultMessage alterPasswordFunc(HttpServletRequest request, HttpServletResponse response,String old_password,String new_password){
        HttpSession session = request.getSession();
        old_password = MD5Util.encrypt(old_password);
        new_password = MD5Util.encrypt(new_password);
        Admin admin = (Admin) session.getAttribute("admin");
        if (old_password.equals(admin.getPassword())){
            admin.setPassword(new_password);
            if (adminService.updateById(admin)){
                session.setAttribute("admin",admin);
            }else{
                return new ResultMessage(false,"修改失败！");
            }
        }else{
            return new ResultMessage(false,"原密码错误，请重新输入！");
        }
        return ResultMessage.success();
    }

    /**
     * 退出登录方法
     * @return
     */
    @RequestMapping("/logout")
    @ResponseBody
    public ResultMessage logoutFunc(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        session.removeAttribute("admin");
        return ResultMessage.success();
    }

    /**
     * 展示admin列表
     * @param page 当前页
     * @param limit 当前显示数据条数
     * @return
     */
    @RequestMapping("/listAdmin")
    @ResponseBody
    public void listAdmin(HttpServletResponse response,int page,int limit){
        IPage<Admin> res = adminService.listAdminByPage(page,limit);
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("total",res.getTotal());
        map.put("data",res.getRecords());
        JsonUtils.jsonArray(map,response);
    }

    /**
     * 修改方法
     * @param admin
     * @return
     */
    @RequestMapping("/updateAdminFunc")
    @ResponseBody
    public ResultMessage updateAdminFunc(Admin admin){
    	admin.setPassword(MD5Util.encrypt(admin.getPassword())); //加密用户密码
        admin.setCertificate(CertificateBulider.buildCertificate(admin));
        Boolean b =  adminService.updateById(admin);
        if (b){
            return ResultMessage.success();
        }
        return ResultMessage.fail();
    }

    /**
     * 添加方法
     * @param admin
     * @return
     */
    @RequestMapping("/addAdminFunc")
    @ResponseBody
    public ResultMessage addAdminFunc(Admin admin){
        Date date = new Date(); //获取当前的系统时间。
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmss");
        String time = dateFormat.format(date);
        admin.setUid(time);
        admin.setCertificate(CertificateBulider.buildCertificate(admin));
        
        admin.setPassword(MD5Util.encrypt(admin.getPassword()));
        Boolean b = adminService.save(admin);
        if (b){
            return ResultMessage.success();
        }
        return ResultMessage.fail();
    }

    /**
     * 删除方法
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteAdminFunc")
    public ResultMessage deleteAdminFunc(@RequestParam(required = false,value = "ids[]") List<String> ids){
        Boolean b = adminService.removeByIds(ids);
        if (b){
            return ResultMessage.success();
        }
        return ResultMessage.fail();
    }


}
